/*
 * 流程监控
 * @Author: gk 
 * @Date: 2018-04-25 14:46:08 
 * @Last Modified by: gk
 * @Last Modified time: 2018-04-27 10:14:49
 */

layui.config({}).use(['element', 'zlConfig', 'zlContext', 'zltreemenu', 'zlSelectMultiple', 'zlPopSourceExt','zlFormulaCmp', 'table', 'layer', 'form', 'zlPinYin', 'upload'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		zltreemenu = layui.zltreemenu,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
		zlConfig = layui.zlConfig,
		statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
		OK = zlConfig.global.result.okState,
		fullheight = 'full-30',
        zlPopSourceExt = layui.zlPopSourceExt,
        zlFormulaCmp = layui.zlFormulaCmp,
		customCurr = 1;

	var treeObj,
		currNode,
		isloadsearch = false,
		treeAction = {
			/**发起刷新明细资料的事件 */
			raiseResDataEvent: function (node) {
				currNode = node;
				if (!node) {
					var nodes = treeObj.getSelectedNodes();
					if (nodes.length > 0)
						currNode = nodes[0];
				}
				layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode);
			},
		};

	//加载树
	treeObj = zltreemenu.render('orgTreeId', {
		dataurl: layui.cache['contentPath'] + '/manager/corefunction/queryorgddata',
		type: 'get',
		tableId: 'tbWorkflow',
		isMove: false
	}, {
		onAsyncSuccess: function (event, treeId, treeNode, msg) {
			treeObj.selectNode(treeObj.getNodes()[0]);
			treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
		},
		onClick: function (event, treeId, treeNode) {
			customCurr = 1;
			treeAction.raiseResDataEvent(treeNode);
		}
	})

	//渲染流程列表
	var workflowTb = table.render({
		elem: '#tbWorkflow',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 20,
		limits: [20, 50, 100, 200, 500, 1000],
		updId: 'E32737C517C94777A4EDBB9CE893A908',
		toolbar: "#toolbarWorkflow",
		defaultToolbar: ['filter'],
		page: true,
		sortload: true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
				}, {
					type: 'checkbox',
					fixed: 'left'
				}, {
					field: 'TASKNAME',
					title: '流程名名称',
					width: 200,
					sort: true
				}, {
					field: 'PROC_INST_ID_',
					title: '流程实例ID',
					width: 200,
					sort: true
				}, {
					field: 'FUNCTIONNAME',
					title: '流程关联的功能',
					width: 200,
					sort: true
				}, {
					field: 'STATENAME',
					title: '当前的流程状态',
					width: 200,
					sort: true
				}, {
					fixed: 'right',
					width: 320,
					title: '操作',
					align: 'center',
					toolbar: '#barWorkflow'
				}
			]
		],
		event: {
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
	});

	var gridAction = {
		currentEditObj: undefined,
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的流程');
				return;
			}
                var frmExportField = [
                    '<div class="layui-form-item" style="margin-bottom: 0;">'
                  , '   <div id="dataFilterTipInfo" class="layui-form-mid layui-word-aux" style="padding: 9px 10px !important;">请编写删除流程对应的业务数据处理，如果不编写默认不处理业务数据，采用的是grovvy脚本,默认传值选中记录的流程id，类型为list&lt;String&gt;,入参名为：ids</div>'
                  , '</div>'
                  , '<div class="layui-form-item">'
                  , '   <div class="layui-col-md12">'
                  , '       <div zl-action="formula"zl-action="formula" name="formula" zlcomponent class="zl-formulacmp"></div>'
                  , '       <label class="layui-form-label">业务数据删除脚本</label>'
                  , '       <div class="layui-input-block">'
                  , '           <button class="layui-btn custom-formula-btn layui-btn-sm" type="button" style="width:75px">自定义</button>'
                  , '           <div id="ace-editor-contianer"></div>'
                  , '        </div>'
                  , '    </div>'
                  , '</div>'
              ];
              layer.open({
                type: 1
                , id: 'exportFieldLayer'
                , title: "编写业务数据删除逻辑"
                , area: ["800px", "450px"]
                , content: frmExportField.join('')
                , btn: ['确定', '取消']
                ,success: function(){
                    $('#ace-editor-contianer').append('<div id="grovvy" name="grovvy" style="min-height: 245px; overflow-y: auto;"></div>');
                    ace.require("ace/ext/language_tools");
                    var aceEditor = ace.edit("grovvy");
                    aceEditor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示
                    aceEditor.getSession().setMode("ace/mode/groovy");//语言
                    aceEditor.getSession().setTabSize(4);
                    aceEditor.setFontSize(14);
                  
                    aceEditor.setOptions({
                        enableBasicAutocompletion: true,
                        enableSnippets: true,
                        enableLiveAutocompletion: true,//只能补全
                    });
                }
                , yes: function (index, layero) {
                    zlContext.confirm('询问', '您确定删除选择的流程吗', function () {
                        var id = gridAction.getCheckTaskId(rows);
                        var aceEditor = ace.edit("grovvy");
                        var groovy  = aceEditor.getValue();
                        var params = {};
                        params.id=id;
                        params.groovy = groovy;
                        zlContext.deletePost(layui.cache['contentPath'] + '/core/workflow/model/deletetask', params, function (data) {
                            if (data[statusName] == OK) {
                                layer.close(index);
                                zlContext.successMsg('删除流程成功！');
                                gridAction.search();
                            } else {
                                zlContext.errorMsg(data[msgName]);
                            }
                        });
                    });
                },
                btn2: function(index, layero){
                    layer.close(index);
                }, cancel: function(index, layero){
                    layer.close(index);
                }
            });
				
		},
		finishTask: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要结束的流程');
				return;
			}
			var id = new Array();
			for (var i = 0; i < rows.length; i++) {
				id.push(rows[i].TASKID);
			}
			zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/finishtask', id.join(','), function (data) {
				if (data[statusName] == OK) {
					zlContext.successMsg('结束流程成功！');
					gridAction.search();
				} else {
					zlContext.errorMsg(data[msgName]);
				}
			});
		},
		goFirstTask: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要退回的流程');
				return;
			}
			zlContext.confirm('询问', '您确定要退回选择的流程吗', function () {
				var id = gridAction.getCheckTaskId(rows);
				zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/revoketask', id, function (data) {
					if (data[statusName] == OK) {
						zlContext.successMsg('退回流程成功！');
						gridAction.search();
					} else {
						zlContext.errorMsg(data[msgName]);
					}

				});
			});

		},
		getCheckTaskId: function (rows) {
			var id = new Array();
			for (var i = 0; i < rows.length; i++) {
				id.push(rows[i].PROC_INST_ID_);
			}
			return id.join(',');
		},
		find: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要查看的流程');
				return;
			}
			zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/findliuc', rows[0].PROC_INST_ID_, function (data) {
				var html = ['<div class="layui-row">', '	<div class="layui-col-md12 docking-fill"><div class="layui-card-body">', '		<table id="tbFindWorkflow" class="layui-hide" lay-filter="tbWorkflow"></table>', '	</div></div>', '</div>']
				layer.open({
					type: 1,
					title: '查看流程',
					id: 'checkProcessLayer',
					area: ['100%', '100%'],
					content: html.join(''),
					response: zlConfig.global.gridResponse,
					success: function (layero, index) {
						table.render({
							elem: '#tbFindWorkflow',
							height: 'full-65',
							page: false,
							sortload: false,
							cols: [
								[ //表头
									{
										type: 'numbers',
										fixed: 'left',
										title: '#'
									}, {
										field: 'AUDITUSER',
										title: '审核人',
										width: 300,
										sort: true
									}, {
										field: 'AUDITTIME',
										title: '审核时间',
										width: 300,
										sort: true
									}, {
										field: 'AUDITRLT',
										title: '操作',
										width: 300,
										sort: true
									}, {
										field: 'AUDITMEMO',
										title: '审核意见',
										sort: true
									}
								]
							],
							data: data.obj,
						});
					}
				});
			});
		},
		agent: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要代理的流程');
				return;
			}
			var settings = {
				tabs: [{
					entryname: 'ORGID',
					name: '机构部门',
					tableUrl: layui.cache['contentPath'] + '/admin/coreuser/queryusersbydeptrole',
					tbmethod: 'post',
					url: layui.cache['contentPath'] + '/manager/coreroleauth/queryOrgddata',
					method: 'get'
				}],
				id: 'RWID',
				name: 'OBJNAME',
				page: 'true',
				limit: 50,
				formtitle: '选择机构人员',
				placeholder: '请选择角色',
				tbmultselect: true,
				titlefield: 'VALUE',
				valuefield: 'KEY',
				params: '{ORGID:&quot;EF137D657144406EBCDE212B3C402361&quot;}',
				buttontype: true,
				parentnode: '.layui-input-block',
				container: '.assignment-box',
				coltitle: [
					[{
						type: 'numbers',
						fixed: 'left',
						title: '#'
					}, {
						type: 'checkbox',
						fixed: 'left'
					}, {
						field: 'OBJNAME',
						title: '姓名',
						width: 100
					}, {
						field: 'DEPTNAME',
						title: '部门',
						width: 100
					}, {
						field: 'ROLENAME',
						title: '角色',
						width: 100
					}, {
						field: 'ORGNAME',
						title: '机构',
						width: 100
					}]
				],
				chosencoltitle: [
					[{
						type: 'numbers',
						fixed: 'left',
						title: '#'
					}, {
						type: 'checkbox',
						fixed: 'left'
					}, {
						field: 'OBJNAME',
						title: '姓名',
						width: 100
					}, {
						field: 'DEPTNAME',
						title: '部门',
						width: 100
					}, {
						field: 'ROLENAME',
						title: '角色',
						width: 100
					}, {
						field: 'ORGNAME',
						title: '机构',
						width: 100
					}]
				]
			}
			zlPopSourceExt.onlyshow(settings, function (data) {
				if (data.length == 0) {
					return;
				}
				var id = new Array();
				for (var i = 0; i < data.length; i++) {
					id.push(data[i].ORGID + "_" + data[i].DEPTID + "_" + data[i].ROLEID + "_" + data[i].RWID);
				}

				zlContext.confirm('询问', '您确定要找人代理吗？', function () {
					zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/agenttask', {
						taskid: rows[0].TASKID,
						userids: id
					}, function (date) {
						zlContext.successMsg('代理流程成功！');
						gridAction.search();
					});
				});
			});

		},
		search: function () {
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			} else if (type == 'new') {
				table.reload('tbWorkflow');
			} else if (type == 'del') {
				table.deleteCheckRows('tbWorkflow');
			}
			form.render();
		}
	}

	$('#btnWorkflowFinish').on('click', function () {
		var checkStatus = table.checkStatus('tbWorkflow'),
			rows = checkStatus.data;
		gridAction.finishTask(rows);
	});
	// $('#btnSeacher').on('click', function () {
	// 	gridAction.search();
	// });
	$('.zl-container').on('keyup','#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
			customCurr = 1;
			
		$('.zl-container').attr('data-search',$(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
	});

	//头工具栏事件
	table.on('toolbar(tbWorkflow)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		var rows = checkStatus.data;
		switch(obj.event){
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'gobackWorkflow':
				gridAction.goFirstTask(rows);
				break;
			case 'deleteWorkflow':
				gridAction.deleteRows(rows);
				break;
		};
	});

	//监听行工具事件
	table.on('tool(tbWorkflow)', function (obj) {
		var row = obj.data, //获得当前行数据
			layEvent = obj.event, //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			rows = new Array();
		rows.push(row);
		gridAction.currentEditObj = obj;
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.deleteRows(rows);
		} else if (layEvent === 'finish') { //结束
			gridAction.finishTask(rows);
		} else if (layEvent === 'first') { //撤销	
			gridAction.goFirstTask(rows);
		} else if (layEvent == 'agent') { //代理
			gridAction.agent(rows);
		} else if (layEvent === 'find') { //查看流程
			gridAction.find(rows);
		}
	});

	//提交
	form.on('submit(frmGridWorkflow)', function (frm) {
		return gridAction.sumbit(frm.field);
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (node) {
		var winIndex = layer.msg('数据查询中，请稍候...', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (id, url, param) {
			workflowTb.reload({
				url: url,
				method: 'post',
				page:{
					curr:customCurr
				},
				where: param,
				done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(winIndex);
					customCurr = curr;
				}
			}, true);
		}
		var params = null;
		var keyvalue = $('#edtSeacherValue').val();
		if (node != null && keyvalue != '') {
			params = {
				ORGID: node.RWID,
				KEYVALUE: keyvalue
			}
			isloadsearch = true;
		} else if (node == null && keyvalue != '') {
			params = {
				KEYVALUE: keyvalue
			}
			isloadsearch = true;
		} else if (node != null && keyvalue == '') {
			params = {
				ORGID: node.RWID
			}
		}
		loadGridData('tbWorkflow', layui.cache['contentPath'] + '/core/workflow/model/querytask', params);
	});
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null);

	
	//iframe自适应
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
    }).resize();

    var formulaCallback = {
        callbackFormula: function(param){
            var aceEditor = ace.edit("grovvy");
            aceEditor.setValue(param['MODELE_VALUE']);
            layer.close(param.addformulaPop);
        }
    };
    
    $("body").on('click', ' .custom-formula-btn', function(){
        var aceEditor = ace.edit("grovvy");
        var text = aceEditor.getValue();
        var formulaSettings = "{'dataurl':'"+layui.cache['contentPath'] + "/manager/coremodeldesign/queryFormulaDesc','method':'post','isordinary':false}";
        zlFormulaCmp.render($('[zl-action="formula"]'),text,formulaSettings,formulaCallback);
    });

});
